package com.cykj.v_m_sprintboot.controller;

import com.alibaba.fastjson.JSONObject;
import com.cykj.v_m_sprintboot.bean.TbUser;
import com.cykj.v_m_sprintboot.service.TbUserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 艾彬
 * 2021-09-26
 */


@RestController
public class UserController {

    @Autowired
    private TbUserService tbUserService;

    private String appid="wxa91bc0bdd694e3a9";//appid需自己提供
    private String secret="61d1fee2fc1c506ed0cad5c50b8bfa1f";//secret需自己提供

    @RequestMapping("/tologin")
    public Map<String, Object> login(@Param("code") String code,String appid,String secret) {
        System.out.println(code+"值");
        //返回map
        Map<String,Object> resMap = new HashMap<>();
        //小程序端发送过来的code
        String result = "";
        String appId = appid;
        String secRet = secret;
        //微信服务器接口
        String url="https://api.weixin.qq.com/sns/jscode2session?appid="+appId+"&secret="+secRet+"&js_code="+code+"&grant_type=authorization_code";
        url+=code+"&grant_type=authorization_code";
        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }finally { // 使用finally块来关闭输入流
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        JSONObject jsonObject = JSONObject.parseObject(result);
        System.out.println(jsonObject);
        String wxOpenid = jsonObject.getString("openid");
        String sessionKey = jsonObject.getString("session_key");

        System.out.println(wxOpenid+"---"+sessionKey);
        //查询用户
//        TbUser tbuser = tbUserService.selectUser(wxOpenid);
//        System.out.println("用户："+username);
        //判断用户是否第一次登录
        //将openId存进数据库，进行用户绑定（理解为注册就行）
        //将用户的uid作为sessionId（我自己这样子做的，你们可以弄得复杂）
        //int sessionId =userService.getUserId(jsonObject.get("openid"))
        //下面展示不使用数据库了，直接传个1

        resMap.put("openid", wxOpenid);//查找的用户信息进行封装返回
        resMap.put("sessionKey", sessionKey);
        return resMap;
         }


    @RequestMapping("/checklogin")
    public Map<String,Object> checklogin(@Param("code") String code,String userName,String userTime,String headImg){
        Map<String,Object> oMap = new HashMap<>();


        System.out.println(code+"值");
        System.out.println("名字："+userName);
        System.out.println("头像路径："+headImg);
        System.out.println("时间："+userTime);

        //小程序端发送过来的code
        String result = "";

        //微信服务器接口
        String url="https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+secret+"&js_code="+code+"&grant_type=authorization_code";

        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }finally { // 使用finally块来关闭输入流
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        JSONObject jsonObject = JSONObject.parseObject(result);
        System.out.println(jsonObject);
        String wxOpenid = jsonObject.getString("openid");
        String sessionKey = jsonObject.getString("session_key");
        System.out.println("--------------------------");
        try {
            //查询用户
            TbUser tbuser = tbUserService.selectUser(wxOpenid);
            System.out.println("用户："+tbuser);
            if (tbuser == null){ //判断用户是否第一次登录

                tbUserService.insertUser(userName,wxOpenid,userTime,headImg);
                System.out.println("成功");

            }

            oMap.put("userID",tbuser.getUserId());
            oMap.put("userName", userName);
            oMap.put("openID", wxOpenid);//查找的用户信息进行封装返回
            oMap.put("headImg", headImg);
            oMap.put("userPoint",tbuser.getUserPoint());
            oMap.put("userPhone",tbuser.getPhone());
            oMap.put("sessionKey",sessionKey);

            oMap.put("uservip",tbuser.getUserVip());
        }catch (Exception e){

            return oMap;
        }


        return oMap;
    }

    @RequestMapping("/obtainPhone")
    public void phone(String token,String encryptedData,String iv){
        System.out.println(token+"--"+encryptedData+","+iv);
    }
    }

